<?php
require_once __DIR__ . '/../vendor/autoload.php';
use Workerman\MySQL\Connection;
use GatewayWorker\Lib\Gateway;
class Events
{
    private static $mysql;
    private static $room = ['casual_high_room'];

    /*
     * 进程启动
     * */
    public static function onWorkerStart(){
        $config = Config::loadConf();
        self::$mysql = new Connection($config['host'],$config['port'],$config['user'],$config['password'],$config['database']);
    }

    /**
     * 收到消息时触发
     * @param int $client_id 发消息的client_id
     * @param mixed $message 消息
     * @return void
     */
    public static function onMessage($client_id, $message){
        //json转为数组格式
        $data = json_decode($message,1);
        switch ($data['event']){
            case 'bind':
                self::bindHandle($client_id,$data);
                break;
            case 'online':
                self::onlineHandle($client_id,$data);
                break;
            case 'room':
                self::roomHandle($client_id,$data);
                break;
        }
    }

    /**
     * 当用户断开连接时触发的方法
     * @param integer $client_id 断开连接的客户端client_id
     * @return void
     */
    public static function onClose($client_id)
    {
        // 广播给所有人
        $data['event'] = 'out';
        $data['user_id'] = $_SESSION['user_id'];
        GateWay::sendToAll(json_encode($data));
    }

    private static function roomHandle($client_id,$data){
        $to_client_id = Gateway::getClientIdByUid($data['to_user_id'])[0];
        Gateway::joinGroup($to_client_id,$data['room']);
        Gateway::joinGroup($client_id,$data['room']);

        Gateway::sendToClient($to_client_id,json_encode($data));
    }

    private static function onlineHandle($client_id,$data){
        $created_at = date('Y-m-d H:i:s');
        if($data['room'] == self::$room[0]){
            $messages_id = self::$mysql->insert('messages')->cols(['user_id'=>$data['user_id'],'content'=>$data['msg'],'room'=>self::$room[0],'created_at'=>$created_at])->query();
        }
        $response['event'] = 'online';
        $response['user_id'] = Gateway::getUidByClientId($client_id);
        $response['room'] = $data['room'];
        $response['msg'] = [
                    'created_at' => $created_at,
                    'msg' => $data['msg'],
                    'name' => $data['name']
                    ];
        Gateway::sendToGroup($data['room'],json_encode($response));
    }

    /*
     * 首次进入绑定
     * */
    private static function bindHandle($client_id,$data){
        $user_id = self::$mysql->insert('users')->cols(['name'=>$data['name']])->query();
        if($user_id){
            //加入微嗨聊天室
            Gateway::setSession($client_id,['name'=>$data['name'],'user_id'=>$user_id]);
            Gateway::bindUid($client_id,$user_id);
            Gateway::joinGroup($client_id,self::$room[0]);
            //查询出所有历史消息并发送给新加入用户
            $data['msg'] = self::$mysql->select('users.name,messages.content as msg,messages.created_at,messages.user_id')->from('messages')->innerJoin('users','messages.user_id = users.id')->where('room = :room')->bindValues(['room'=>self::$room[0]])->query();
            $data['user_id'] = $user_id;
            $data['room'] = self::$room[0];
            $data['live_users'] = Gateway::getClientSessionsByGroup(self::$room[0]);
            Gateway::sendToClient($client_id,json_encode($data));

            //广播给所有在微嗨聊天室的用户
            $response['event'] = 'welcome';
            $response['user'] = Gateway::getSession($client_id);
            Gateway::sendToGroup(self::$room[0],json_encode($response));
        }
    }



}